#include <stdlib.h>
#include <string.h>

#include <curl/curl.h>

#include "membuf.h"

static size_t
write_callback(char *ptr, size_t size, size_t nmemb, void *userdata)
{
	struct membuf *buf_obj = (struct membuf *)userdata;
	buf_obj->data_len += nmemb;
	if (buf_obj->data_len > buf_obj->total_bytes) {
		buf_obj->total_bytes += nmemb + INPUT_WEB_BUF_SIZE;
		buf_obj->start_ptr = realloc(buf_obj->start_ptr,
				buf_obj->total_bytes);
	}
	memcpy((char *)buf_obj->start_ptr + buf_obj->offset, ptr, nmemb);
	buf_obj->offset += nmemb;
	return nmemb * size;
}

size_t
read_kernel_org_site(struct membuf *bufobj)
{
	CURL *esy_handle = curl_easy_init();
	CURLcode retcode;
	if (!esy_handle)
		return 0UL;
	curl_easy_setopt(esy_handle, CURLOPT_URL, "https://kernel.org/");
	curl_easy_setopt(esy_handle, CURLOPT_WRITEDATA, (void *)bufobj);
	curl_easy_setopt(esy_handle, CURLOPT_WRITEFUNCTION, write_callback);
	retcode = curl_easy_perform(esy_handle);
	if (retcode != CURLE_OK)
		bufobj->data_len = 0UL;
	curl_easy_cleanup(esy_handle);
	return bufobj->data_len;
}

